package com.ruoyi.quantify.service.impl;

import java.util.List;

import com.ruoyi.base.domain.BaseClass;
import com.ruoyi.base.domain.BaseSection;
import com.ruoyi.base.domain.BaseSemster;
import com.ruoyi.base.domain.BaseStudent;
import com.ruoyi.base.mapper.BaseClassMapper;
import com.ruoyi.base.mapper.BaseSectionMapper;
import com.ruoyi.base.mapper.BaseSemsterMapper;
import com.ruoyi.base.mapper.BaseStudentMapper;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ValidationUtils;
import com.ruoyi.common.utils.bean.BeanUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.quantify.mapper.QuantifyRuleMapper;
import com.ruoyi.quantify.mapper.QuantifyStudentMapper;
import com.ruoyi.quantify.domain.QuantifyRule;
import com.ruoyi.quantify.domain.QuantifyStudent;
import com.ruoyi.quantify.service.IQuantifyStudentService;

/**
 * 量化考核Service业务层处理
 * 
 * @author yepanpan
 * @date 2021-05-14
 */
@Service
public class QuantifyStudentServiceImpl implements IQuantifyStudentService 
{
    private static final Logger log = LoggerFactory.getLogger(QuantifyStudentServiceImpl.class);
    @Autowired
    private QuantifyStudentMapper quantifyStudentMapper;
    @Autowired
    private BaseStudentMapper baseStudentMapper;
    @Autowired
    private QuantifyRuleMapper quantifyRuleMapper;
    @Autowired
    private BaseSectionMapper baseSectionMapper;
    @Autowired
    private BaseClassMapper baseClassMapper;
    @Autowired
    private BaseSemsterMapper baseSemsterMapper;

    /**
     * 查询量化考核
     * 
     * @param id 量化考核ID
     * @return 量化考核
     */
    @Override
    public QuantifyStudent selectQuantifyStudentById(Long id)
    {
        return quantifyStudentMapper.selectQuantifyStudentById(id);
    }

    /**
     * 查询量化考核列表
     * 
     * @param quantifyStudent 量化考核
     * @return 量化考核
     */
    @Override
    public List<QuantifyStudent> selectQuantifyStudentList(QuantifyStudent quantifyStudent)
    {
        return quantifyStudentMapper.selectQuantifyStudentList(quantifyStudent);
    }

    /**
     * 新增量化考核
     * 
     * @param quantifyStudent 量化考核
     * @return 结果
     */
    @Override
    @Transactional
    public int insertQuantifyStudent(QuantifyStudent quantifyStudent)
    {
    	QuantifyRule rule = quantifyRuleMapper.selectQuantifyRuleById(quantifyStudent.getRuleId());
    	quantifyStudent.setScore(rule.getScore());
    	quantifyStudent.setMode(rule.getMode());
        quantifyStudent.setCreateTime(DateUtils.getNowDate());
        quantifyStudent.setCreateBy(SecurityUtils.getUsername());
        if(quantifyStudent.getStuId() != null) {
        	BaseStudent s = baseStudentMapper.findStudentByUser(quantifyStudent.getStuId());
        	quantifyStudent.setStuCode(s.getCode());
        	quantifyStudent.setStuName(s.getName());
        	return quantifyStudentMapper.insertQuantifyStudent(quantifyStudent);
        }else {

            int count = 0;
            for(Long stuId:quantifyStudent.getStuIds()) {
            	if(StringUtils.isNull(stuId)) continue;
            	
            	QuantifyStudent stu = new QuantifyStudent();
            	BeanUtils.copyBeanProp(stu, quantifyStudent);

            	stu.setStuId(stuId);
            	BaseStudent s = baseStudentMapper.findStudentByUser(stuId);
            	stu.setStuCode(s.getCode());
            	stu.setStuName(s.getName());
            	
            	quantifyStudentMapper.insertQuantifyStudent(stu);
            	count ++;
            }
            return count;
        }
    }

    /**
     * 修改量化考核
     * 
     * @param quantifyStudent 量化考核
     * @return 结果
     */
    @Override
    public int updateQuantifyStudent(QuantifyStudent quantifyStudent)
    {
        quantifyStudent.setUpdateTime(DateUtils.getNowDate());
        quantifyStudent.setUpdateBy(SecurityUtils.getUsername());
        return quantifyStudentMapper.updateQuantifyStudent(quantifyStudent);
    }

    /**
     * 批量删除量化考核
     * 
     * @param ids 需要删除的量化考核ID
     * @return 结果
     */
    @Override
    public int deleteQuantifyStudentByIds(Long[] ids)
    {
        return quantifyStudentMapper.deleteQuantifyStudentByIds(ids);
    }

    /**
     * 删除量化考核信息
     * 
     * @param id 量化考核ID
     * @return 结果
     */
    @Override
    public int deleteQuantifyStudentById(Long id)
    {
        return quantifyStudentMapper.deleteQuantifyStudentById(id);
    }
    

    /**
     * 导入数据
     * 
     * @param list 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String imports(List<QuantifyStudent> list, Boolean isUpdateSupport, String operName) {

		if (StringUtils.isNull(list) || list.size() == 0) {
			throw new CustomException("导入数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
       
		for (QuantifyStudent vo : list) {
			List<String> vs = ValidationUtils.validate(vo);
			if (vs != null) {
				failureNum++;
				failureMsg.append(
						"<br/>" + failureNum + "、学生 " + vo.getStuName() + " 数据不完整：" + CollectionUtils.join(vs, ","));
				continue;
			}
			try {
				
				BaseSemster semster = baseSemsterMapper.findSemsterByName(vo.getSemName());
				if(semster == null) {
					throw new CustomException("学期不"+vo.getSemName()+"存在");
				}else {
					vo.setSemId(semster.getId());
				}
				 // 验证班级是否存在
            	BaseClass dd = baseClassMapper.findClassByName(vo.getClassName());
            	if(dd == null) {
            		throw new CustomException("班级不"+vo.getClassName()+"存在");
            	}
            	vo.setClassId(dd.getId());
            	
            	BaseStudent bsc = new BaseStudent();
            	bsc.setCode(vo.getStuCode());
            	bsc.setName(vo.getStuName());
            	bsc.setClassId(vo.getClassId());
            	
            	BaseStudent s = baseStudentMapper.findBaseStudent(bsc);
            	if(s == null) {
            		throw new CustomException("学生信息不存在："+vo.getStuName()+"，"+vo.getStuCode());
            	}
            	vo.setStuId(s.getUserId());
            	
            	if(StringUtils.isNoneBlank(vo.getSectionName())) {
                	BaseSection sc = baseSectionMapper.findSectionByName(vo.getSectionName());
                	if(sc != null) {
                		vo.setSectionId(sc.getId());
                	}
            	}
            	QuantifyRule rule = quantifyRuleMapper.findQuantifyRuleByName(vo.getRuleName());
            	if(rule == null) {
            		throw new CustomException("规则信息不存在："+vo.getRuleName());
            	}else {
            		vo.setRuleId(rule.getId());
            	}
            	
				// 查找旧数据
            	QuantifyStudent cond = new QuantifyStudent();
				cond.setStuId(vo.getStuId());
				cond.setDates(vo.getDates());
				cond.setSectionId(vo.getSectionId());
				cond.setRuleId(vo.getRuleId());
				List<QuantifyStudent> old = quantifyStudentMapper.selectQuantifyStudentList(cond);
				if (old == null || old.size() == 0) {					
					this.insertQuantifyStudent(vo);
					successNum++;
					successMsg.append("<br/>" + successNum + "、学生 " + vo.getStuName() + " 的量化考核信息导入成功");
				} else if (isUpdateSupport) {
					vo.setId(old.get(0).getId());
					this.updateQuantifyStudent(vo);
					successNum++;
					successMsg.append("<br/>" + successNum + "、学生 " + vo.getStuName() + " 的量化考核信息更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、学生 " + vo.getStuName() + " 的量化考核信息已存在");
				}
				
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、学生 " + vo.getStuName() + " 的量化考核信息导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
    }
}
